﻿using System;
using System.Drawing;
using System.Web;

namespace sBlog.Net.Upload
{
    /// <summary>
    /// Summary description for MlogUploadUserCover
    /// </summary>
    public class MlogUploadUserCover : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Expires = -1;
            if (context.Request["UserId"] != null)
            {
                string userId = context.Request["UserId"];
                string fName = Guid.NewGuid().ToString() + ".jpg";
                try
                {
                    HttpPostedFile postedFile = context.Request.Files["Filedata"];
                    Byte[] buffer = new Byte[1];

                    string ftpUploadUrl = string.Empty;
                    string strFtpAddress = System.Configuration.ConfigurationManager.AppSettings["ftpServer"].ToString() + "/Mlog/UploadUserCover";
                    string strFolderUser = clsFunction.GetFolderUser(strFtpAddress, userId);
                    clsFunction.CreateUserFolder(strFtpAddress, userId, System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString(), System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString());

                    //1000x280_
                    Bitmap bmp1000 = new Bitmap(postedFile.InputStream);
                    if (bmp1000.Width > 1000 || bmp1000.Height > 280)
                    {
                        Bitmap bmpResize = ImageUtility.cropImageRectangleCenter(bmp1000, new Rectangle(0, 0, 30, 30));
                        buffer = ImageUtility.SaveImage(bmpResize, 100L);
                        bmp1000.Dispose();
                        bmpResize.Dispose();
                    }
                    else buffer = ImageUtility.SaveImage(bmp1000, 100L);
                    ftpUploadUrl = strFolderUser + "/1000x280_" + fName;
                    clsFunction.UpFileServer(ftpUploadUrl, buffer);

                    string strDate = DateTime.Now.Year.ToString() + DateTime.Now.ToString("MM");

                    context.Response.StatusCode = 200;
                    context.Response.Write(strDate + fName);
                }
                catch (Exception ex)
                {
                    clsFunction.Log("Loi ThumbUserAvatar: " + ex.Message);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}